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
|
// Package captokens provides canonical token serialization and validation
// for capability-based authorization tokens.
package captokens
import (
"bytes"
"fmt"
"sort"
"strconv"
"strings"
)
// KnownMetadataFields lists all allowed metadata fields (exhaustive).
// Fields with $ or _ prefix must be in this list.
var KnownMetadataFields = map[string]bool{
"$tok_id": true, // Token type identifier
"_session": true, // Session UUID
"_issued": true, // ISO8601 timestamp
"_expires": true, // ISO8601 timestamp
"_sig": true, // Base64-encoded signature (not hashed)
}
// IsValidFieldName checks if a field name follows naming rules.
// Allowed characters: [_$\-a-zA-Z0-9]
// Must be non-empty.
func IsValidFieldName(name string) bool {
if len(name) == 0 {
return false
}
for _, c := range name {
if !((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '_' || c == '$' || c == '-') {
return false
}
}
return true
}
// IsKnownMetadataField checks if a field name is a known metadata field.
func IsKnownMetadataField(name string) bool {
return KnownMetadataFields[name]
}
// CanonicalTokenBytes generates canonical bytes for token signing/verification.
// The _sig field is excluded from canonicalization.
// Returns deterministic bytes with sorted keys and validated field names.
func CanonicalTokenBytes(token map[string]any) ([]byte, error) {
// Extract and validate all fields except "_sig"
fields := make(map[string]string)
for key, value := range token {
if key == "_sig" {
continue
}
// Validate field name
if !IsValidFieldName(key) {
return nil, fmt.Errorf("invalid field name: %s", key)
}
// Validate reserved fields
if strings.HasPrefix(key, "$") || strings.HasPrefix(key, "_") {
if !IsKnownMetadataField(key) {
return nil, fmt.Errorf("unknown metadata field: %s", key)
}
}
// Serialize value (validates nested keys recursively)
serialized, err := serializeValue(value)
if err != nil {
return nil, fmt.Errorf("field %s: %w", key, err)
}
fields[key] = serialized
}
// Sort keys by ASCII lexicographic order
keys := make([]string, 0, len(fields))
for key := range fields {
keys = append(keys, key)
}
sort.Strings(keys)
// Concatenate: key=value\n
var buf bytes.Buffer
for _, key := range keys {
buf.WriteString(key)
buf.WriteString("=")
buf.WriteString(fields[key])
buf.WriteString("\n")
}
return buf.Bytes(), nil
}
// serializeValue serializes a value to canonical string format.
// Handles: string, number, bool, null, array, object.
// Validates nested object keys recursively.
func serializeValue(value any) (string, error) {
switch v := value.(type) {
case string:
return v, nil
case float64:
// Canonical number format
if v == float64(int64(v)) {
// Integer value - no decimal point
return strconv.FormatInt(int64(v), 10), nil
}
// Float value - use shortest representation
return strconv.FormatFloat(v, 'g', -1, 64), nil
case int:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(v, 10), nil
case bool:
if v {
return "true", nil
}
return "false", nil
case nil:
return "null", nil
case []any:
// Array: [elem1,elem2,elem3]
var buf bytes.Buffer
buf.WriteString("[")
for i, item := range v {
if i > 0 {
buf.WriteString(",")
}
serialized, err := serializeValue(item)
if err != nil {
return "", fmt.Errorf("array element %d: %w", i, err)
}
buf.WriteString(serialized)
}
buf.WriteString("]")
return buf.String(), nil
case map[string]any:
// Object: {key1=val1,key2=val2} with sorted keys
// Validate all keys follow naming rules
keys := make([]string, 0, len(v))
for key := range v {
if !IsValidFieldName(key) {
return "", fmt.Errorf("invalid nested key: %s", key)
}
keys = append(keys, key)
}
sort.Strings(keys)
var buf bytes.Buffer
buf.WriteString("{")
for i, key := range keys {
if i > 0 {
buf.WriteString(",")
}
buf.WriteString(key)
buf.WriteString("=")
serialized, err := serializeValue(v[key])
if err != nil {
return "", fmt.Errorf("nested field %s: %w", key, err)
}
buf.WriteString(serialized)
}
buf.WriteString("}")
return buf.String(), nil
default:
return "", fmt.Errorf("unsupported value type: %T", value)
}
}
|