1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
package main
// The viewer frame's own routes, /frame/{cap}/….
//
// The PDF viewer on a file page runs in a frame sandboxed without
// allow-same-origin, so that a bug in pdf.js lands in an opaque origin that
// cannot read the mirror (campusweb(7), COURSE CONTENT IS TEXT). The price is
// that whatever the viewer fetches is a cross-origin request from "null": it
// carries no cookie and no HTTP authentication. Anything placed in front of
// campusweb that recognises the reader by those — the passkey gate on legosi —
// cannot let the viewer's requests through, and must not let everybody's.
//
// So the frame's requests are authorised by their URL. A capability names one
// file version and carries an HMAC over it, under the key in state that never
// leaves the database; only a page campusweb has served contains one, and a
// page elsewhere cannot read campusweb's pages. It does not expire: the viewer
// keeps posting notes to it for as long as the tab is open. Replacing the key
// revokes every capability at once.
//
// Parse, don't validate: a capability is turned into a frameGrant once, and
// the handlers take the file and version from the grant, never from anything
// else in the request, so a valid capability cannot be pointed at another
// file.
//
// Everything the reader sees and links to stays on the routes it always had;
// these are only ever in the frame's address. See campusweb(1), ROUTES.
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
"codeberg.org/Profpatsch/Profpatsch/users/Profpatsch/pdfjs"
)
// frameGrant is what a valid capability allows: reading and annotating one
// version of one file. It is only made by parseFrameCap.
type frameGrant struct {
fileID string
version int
}
func (s *server) frameMAC(fileID string, n int) string {
m := hmac.New(sha256.New, s.annotationKey())
fmt.Fprintf(m, "frame\x00%s\x00%d", fileID, n)
return hex.EncodeToString(m.Sum(nil))
}
// frameCap is the capability for a file version: "<file>.<version>.<mac>".
// Stud.IP's ids are hex, so the dots are unambiguous.
func (s *server) frameCap(fileID string, n int) string {
return fmt.Sprintf("%s.%d.%s", fileID, n, s.frameMAC(fileID, n))
}
var errBadCap = errors.New("wrong or unknown viewer address; reload the file page")
func (s *server) parseFrameCap(c string) (frameGrant, error) {
parts := strings.Split(c, ".")
if len(parts) != 3 || parts[0] == "" {
return frameGrant{}, errBadCap
}
n, err := strconv.Atoi(parts[1])
if err != nil || n < 1 || strconv.Itoa(n) != parts[1] {
return frameGrant{}, errBadCap
}
if !hmac.Equal([]byte(parts[2]), []byte(s.frameMAC(parts[0], n))) {
return frameGrant{}, errBadCap
}
return frameGrant{fileID: parts[0], version: n}, nil
}
// frameURLs are the document and save URLs for the viewer on a file page.
func (s *server) frameURLs(fileID string, n int) (pdf, notes string) {
base := "/frame/" + s.frameCap(fileID, n)
return base + "/pdf", base + "/notes"
}
// framePositionURL is where the viewer reports the reader's position.
func (s *server) framePositionURL(fileID string, n int) string {
return "/frame/" + s.frameCap(fileID, n) + "/position"
}
// framed wraps a frame handler: the capability is parsed before anything
// else, and the handler gets the grant. Every frame response says so to the
// opaque origin it goes to, and sends no referrer, so a link followed out of
// a PDF does not carry the capability along.
func (s *server) framed(h func(http.ResponseWriter, *http.Request, frameGrant)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Referrer-Policy", "no-referrer")
g, err := s.parseFrameCap(r.PathValue("cap"))
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
h(w, r, g)
}
}
// handleFramePDF serves the document the viewer opens: the reader's annotated
// copy of the version if there is one, otherwise the upstream bytes. It is
// what the file page picked before; a save changes it, hence no-cache.
func (s *server) handleFramePDF(w http.ResponseWriter, r *http.Request, g frameGrant) {
f, err := file(s.db.Read, g.fileID)
if err != nil {
s.fail(w, r, err)
return
}
name := f.Name
a, err := annotation(s.db.Read, g.fileID, g.version)
sum := a.Sha256
if errors.Is(err, errNotFound) {
var v versionRow
v, err = version(s.db.Read, g.fileID, g.version)
sum = v.Sha256
} else if err == nil {
name = annotatedName(f.Name, g.version)
}
if err != nil {
s.fail(w, r, err)
return
}
b, err := s.db.openBytes(sum)
if err != nil {
s.fail(w, r, err)
return
}
defer b.Close()
if head, err := b.head(sniffLen); err != nil || !pdfjs.LooksLikePDF(head) {
s.fail(w, r, fmt.Errorf("%w: not a PDF", errNotFound))
return
}
// The viewer fetches it in ranges; if a save lands between two of them,
// its If-Range no longer matches and it is sent the new document whole.
pdfjs.SetPDFHeaders(w, name)
serveOpen(w, r, sum, cacheRevalidate, b)
}
// handleFrameNotes stores the annotated document the viewer frame sends. It
// answers plain text, which the save shim shows when it is not a 2xx.
func (s *server) handleFrameNotes(w http.ResponseWriter, r *http.Request, g frameGrant) {
fail := func(status int, format string, args ...any) {
http.Error(w, fmt.Sprintf(format, args...), status)
}
var have int
s.db.Read.QueryRow(`SELECT count(*) FROM file_versions WHERE file_id = ? AND n = ?`, g.fileID, g.version).Scan(&have)
if have == 0 {
fail(http.StatusNotFound, "no version %d of this file", g.version)
return
}
max := s.sync.maxFile
data, err := io.ReadAll(io.LimitReader(r.Body, max+1))
if err != nil {
fail(http.StatusBadRequest, "read: %v", err)
return
}
if int64(len(data)) > max {
fail(http.StatusRequestEntityTooLarge, "larger than --max-file-size (%d bytes)", max)
return
}
if !pdfjs.LooksLikePDF(data) {
fail(http.StatusBadRequest, "not a PDF")
return
}
if err := storeAnnotations(s.db.Write, g.fileID, g.version, data, time.Now()); err != nil {
log.Printf("annotations %s v%d: %v", g.fileID, g.version, err)
fail(http.StatusInternalServerError, "store: %v", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleFramePosition stores where the reader is in the version, as the
// viewer's position shim sends it: "page=3&top=512". The next file page opens
// the viewer there. The page is not checked against the document, which
// campusweb does not read; pdf.js ignores a page it does not have.
func (s *server) handleFramePosition(w http.ResponseWriter, r *http.Request, g frameGrant) {
data, err := io.ReadAll(io.LimitReader(r.Body, 256))
if err != nil {
http.Error(w, "read: "+err.Error(), http.StatusBadRequest)
return
}
p, err := pdfjs.ParsePosition(string(data))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var have int
s.db.Read.QueryRow(`SELECT count(*) FROM file_versions WHERE file_id = ? AND n = ?`, g.fileID, g.version).Scan(&have)
if have == 0 {
http.Error(w, fmt.Sprintf("no version %d of this file", g.version), http.StatusNotFound)
return
}
if err := storePosition(s.db.Write, g.fileID, g.version, p, time.Now()); err != nil {
log.Printf("position %s v%d: %v", g.fileID, g.version, err)
http.Error(w, "store: "+err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
|