1package connect
2
3import (
4	"github.com/hashicorp/consul/agent/structs"
5)
6
7// AuthorizeIntentionTarget determines whether the destination is covered by the given intention
8// and whether the intention action allows a connection.
9// This is a generalized version of the old CertURI.Authorize(), and can be evaluated against sources or destinations.
10//
11// The return value of `auth` is only valid if the second value `match` is true.
12// If `match` is false, then the intention doesn't match this target and any result should be ignored.
13func AuthorizeIntentionTarget(
14	target, targetNS string,
15	ixn *structs.Intention,
16	matchType structs.IntentionMatchType,
17) (auth bool, match bool) {
18
19	switch matchType {
20	case structs.IntentionMatchDestination:
21		if ixn.DestinationNS != structs.WildcardSpecifier && ixn.DestinationNS != targetNS {
22			// Non-matching namespace
23			return false, false
24		}
25
26		if ixn.DestinationName != structs.WildcardSpecifier && ixn.DestinationName != target {
27			// Non-matching name
28			return false, false
29		}
30
31	case structs.IntentionMatchSource:
32		if ixn.SourceNS != structs.WildcardSpecifier && ixn.SourceNS != targetNS {
33			// Non-matching namespace
34			return false, false
35		}
36
37		if ixn.SourceName != structs.WildcardSpecifier && ixn.SourceName != target {
38			// Non-matching name
39			return false, false
40		}
41
42	default:
43		// Reject on any un-recognized match type
44		return false, false
45	}
46
47	// The name and namespace match, so the destination is covered
48	return ixn.Action == structs.IntentionActionAllow, true
49}
50