/
accessctl.go
94 lines (79 loc) · 2.53 KB
/
accessctl.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
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
// Package accessctl implements access control for an Oasis node.
package accessctl
import (
"crypto/ed25519"
"crypto/x509"
"fmt"
"github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
)
// Subject is an access control subject.
type Subject string
// AnySubject is a wildcard subject. When set for an action in a policy, it matches any subject.
const AnySubject Subject = "*"
// SubjectFromX509Certificate returns a Subject from the given X.509
// certificate.
func SubjectFromX509Certificate(cert *x509.Certificate) Subject {
pk, ok := cert.PublicKey.(ed25519.PublicKey)
if !ok {
// This should never happen if certificates are properly verified.
return ""
}
var spk signature.PublicKey
if err := spk.UnmarshalBinary(pk[:]); err != nil {
// This should NEVER happen.
return ""
}
return SubjectFromPublicKey(spk)
}
// SubjectFromPublicKey returns a Subject from the given public key.
func SubjectFromPublicKey(pubKey signature.PublicKey) Subject {
return Subject(pubKey.String())
}
// Action is an access control action.
type Action string
// Policy maps from Actions to a mapping from Subjects to booleans indicating
// whether the given subject is allowed to perform the given action or not.
//
// The policy is not safe for concurrent use.
type Policy map[Action]map[Subject]bool
// NewPolicy returns an empty policy.
func NewPolicy() Policy {
return make(Policy)
}
// Allow adds a policy rule that allows the given Subject to perform the given
// Action.
func (p Policy) Allow(sub Subject, act Action) {
if p[act] == nil {
p[act] = make(map[Subject]bool)
}
p[act][sub] = true
}
// AllowAll adds a policy rule that allows anyone to perform the given action.
// The effect is similar as defining the action to have no access control, but is
// better suited for configuration that depends on runtime parameters.
func (p Policy) AllowAll(act Action) {
if p[act] == nil {
p[act] = make(map[Subject]bool)
}
p[act][AnySubject] = true
}
// Deny removes a policy rule that allows the given Subject to perform the
// given Action.
func (p Policy) Deny(sub Subject, act Action) {
if p[act] == nil {
return
}
delete(p[act], sub)
}
// IsAllowed returns a boolean indicating whether the given Subject is allowed
// to perform the given Action under the current Policy.
func (p Policy) IsAllowed(sub Subject, act Action) bool {
if p[act] == nil {
return false
}
return p[act][AnySubject] || p[act][sub]
}
// String returns the string representation of the policy.
func (p Policy) String() string {
return fmt.Sprintf("%#v", p)
}