-
Notifications
You must be signed in to change notification settings - Fork 9
/
wire.go
55 lines (44 loc) · 1.28 KB
/
wire.go
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package csrf
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
"namespacelabs.dev/foundation/framework/resources"
)
var protect mux.MiddlewareFunc
func Protect(h http.HandlerFunc) http.Handler {
if protect == nil {
panic("protect is nil, missing dependency on namespacelabs.dev/foundation/go/std/go/http/csrf?")
}
return protect(h)
}
func Prepare(ctx context.Context) error {
token, err := readSecretToken()
if err != nil {
return fmt.Errorf("failed to read secret token: %w", err)
}
key, err := base64.RawStdEncoding.DecodeString(string(token))
if err != nil {
return fmt.Errorf("failed to decode key: %v", err)
}
if len(key) != 32 {
return fmt.Errorf("expected a key that is 32 bytes long, got %d", len(key))
}
protect = csrf.Protect(key)
return nil
}
const secretTokenRef = "namespacelabs.dev/foundation/std/go/http/csrf:token-secret-resource"
func readSecretToken() ([]byte, error) {
rs, err := resources.LoadResources()
if err != nil {
log.Fatal(err)
}
return resources.ReadSecret(rs, secretTokenRef)
}