-
Notifications
You must be signed in to change notification settings - Fork 14
/
util.go
72 lines (66 loc) · 2.66 KB
/
util.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
/*
* Copyright (C) 2021 Nuts community
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package doc
import (
"fmt"
"github.com/nuts-foundation/go-did"
"github.com/nuts-foundation/go-did/did"
"github.com/nuts-foundation/nuts-node/vdr/types"
"strings"
)
const serviceTypeQueryParameter = "type"
const serviceEndpointPath = "serviceEndpoint"
// MakeServiceReference creates a service reference, which can be used as query when looking up services.
func MakeServiceReference(subjectDID did.DID, serviceType string) ssi.URI {
ref := subjectDID.URI()
ref.Opaque += "/" + serviceEndpointPath
ref.Fragment = ""
ref.RawQuery = fmt.Sprintf("%s=%s", serviceTypeQueryParameter, serviceType)
return ref
}
// IsServiceReference checks whether the given endpoint string looks like a service reference (e.g. did:nuts:1234/serviceType?type=HelloWorld).
func IsServiceReference(endpoint string) bool {
return strings.HasPrefix(endpoint, "did:")
}
// ValidateServiceReference checks whether the given URI matches the format for a service reference.
func ValidateServiceReference(endpointURI ssi.URI) error {
// Parse it as DID URL since DID URLs are rootless and thus opaque (RFC 3986), meaning the path will be part of the URI body, rather than the URI path.
// For DID URLs the path is parsed properly.
didEndpointURL, err := did.ParseDIDURL(endpointURI.String())
if err != nil {
return types.ErrInvalidServiceQuery
}
if didEndpointURL.Path != serviceEndpointPath {
// Service reference doesn't refer to `/serviceEndpoint`
return types.ErrInvalidServiceQuery
}
queriedServiceType := endpointURI.Query().Get(serviceTypeQueryParameter)
if len(queriedServiceType) == 0 {
// Service reference doesn't contain `type` query parameter
return types.ErrInvalidServiceQuery
}
if len(endpointURI.Query()[serviceTypeQueryParameter]) > 1 {
// Service reference contains more than 1 `type` query parameter
return types.ErrInvalidServiceQuery
}
if len(endpointURI.Query()) > 1 {
// Service reference contains more than just `type` query parameter
return types.ErrInvalidServiceQuery
}
return nil
}