engine.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package policy_engine
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. )
  12. // PolicyEvaluationResult represents the result of policy evaluation
  13. type PolicyEvaluationResult int
  14. const (
  15. PolicyResultDeny PolicyEvaluationResult = iota
  16. PolicyResultAllow
  17. PolicyResultIndeterminate
  18. )
  19. // PolicyEvaluationContext manages policy evaluation for a bucket
  20. type PolicyEvaluationContext struct {
  21. bucketName string
  22. policy *CompiledPolicy
  23. cache *PolicyCache
  24. mutex sync.RWMutex
  25. }
  26. // PolicyEngine is the main policy evaluation engine
  27. type PolicyEngine struct {
  28. contexts map[string]*PolicyEvaluationContext
  29. mutex sync.RWMutex
  30. }
  31. // NewPolicyEngine creates a new policy evaluation engine
  32. func NewPolicyEngine() *PolicyEngine {
  33. return &PolicyEngine{
  34. contexts: make(map[string]*PolicyEvaluationContext),
  35. }
  36. }
  37. // SetBucketPolicy sets the policy for a bucket
  38. func (engine *PolicyEngine) SetBucketPolicy(bucketName string, policyJSON string) error {
  39. policy, err := ParsePolicy(policyJSON)
  40. if err != nil {
  41. return fmt.Errorf("invalid policy: %w", err)
  42. }
  43. compiled, err := CompilePolicy(policy)
  44. if err != nil {
  45. return fmt.Errorf("failed to compile policy: %w", err)
  46. }
  47. engine.mutex.Lock()
  48. defer engine.mutex.Unlock()
  49. context := &PolicyEvaluationContext{
  50. bucketName: bucketName,
  51. policy: compiled,
  52. cache: NewPolicyCache(),
  53. }
  54. engine.contexts[bucketName] = context
  55. glog.V(2).Infof("Set bucket policy for %s", bucketName)
  56. return nil
  57. }
  58. // GetBucketPolicy gets the policy for a bucket
  59. func (engine *PolicyEngine) GetBucketPolicy(bucketName string) (*PolicyDocument, error) {
  60. engine.mutex.RLock()
  61. defer engine.mutex.RUnlock()
  62. context, exists := engine.contexts[bucketName]
  63. if !exists {
  64. return nil, fmt.Errorf("no policy found for bucket %s", bucketName)
  65. }
  66. return context.policy.Document, nil
  67. }
  68. // DeleteBucketPolicy deletes the policy for a bucket
  69. func (engine *PolicyEngine) DeleteBucketPolicy(bucketName string) error {
  70. engine.mutex.Lock()
  71. defer engine.mutex.Unlock()
  72. delete(engine.contexts, bucketName)
  73. glog.V(2).Infof("Deleted bucket policy for %s", bucketName)
  74. return nil
  75. }
  76. // EvaluatePolicy evaluates a policy for the given arguments
  77. func (engine *PolicyEngine) EvaluatePolicy(bucketName string, args *PolicyEvaluationArgs) PolicyEvaluationResult {
  78. engine.mutex.RLock()
  79. context, exists := engine.contexts[bucketName]
  80. engine.mutex.RUnlock()
  81. if !exists {
  82. return PolicyResultIndeterminate
  83. }
  84. return engine.evaluateCompiledPolicy(context.policy, args)
  85. }
  86. // evaluateCompiledPolicy evaluates a compiled policy
  87. func (engine *PolicyEngine) evaluateCompiledPolicy(policy *CompiledPolicy, args *PolicyEvaluationArgs) PolicyEvaluationResult {
  88. // AWS Policy evaluation logic:
  89. // 1. Check for explicit Deny - if found, return Deny
  90. // 2. Check for explicit Allow - if found, return Allow
  91. // 3. If no explicit Allow is found, return Deny (default deny)
  92. hasExplicitAllow := false
  93. for _, stmt := range policy.Statements {
  94. if engine.evaluateStatement(&stmt, args) {
  95. if stmt.Statement.Effect == PolicyEffectDeny {
  96. return PolicyResultDeny // Explicit deny trumps everything
  97. }
  98. if stmt.Statement.Effect == PolicyEffectAllow {
  99. hasExplicitAllow = true
  100. }
  101. }
  102. }
  103. if hasExplicitAllow {
  104. return PolicyResultAllow
  105. }
  106. return PolicyResultDeny // Default deny
  107. }
  108. // evaluateStatement evaluates a single policy statement
  109. func (engine *PolicyEngine) evaluateStatement(stmt *CompiledStatement, args *PolicyEvaluationArgs) bool {
  110. // Check if action matches
  111. if !engine.matchesPatterns(stmt.ActionPatterns, args.Action) {
  112. return false
  113. }
  114. // Check if resource matches
  115. if !engine.matchesPatterns(stmt.ResourcePatterns, args.Resource) {
  116. return false
  117. }
  118. // Check if principal matches (if specified)
  119. if len(stmt.PrincipalPatterns) > 0 {
  120. if !engine.matchesPatterns(stmt.PrincipalPatterns, args.Principal) {
  121. return false
  122. }
  123. }
  124. // Check conditions
  125. if len(stmt.Statement.Condition) > 0 {
  126. if !EvaluateConditions(stmt.Statement.Condition, args.Conditions) {
  127. return false
  128. }
  129. }
  130. return true
  131. }
  132. // matchesPatterns checks if a value matches any of the compiled patterns
  133. func (engine *PolicyEngine) matchesPatterns(patterns []*regexp.Regexp, value string) bool {
  134. for _, pattern := range patterns {
  135. if pattern.MatchString(value) {
  136. return true
  137. }
  138. }
  139. return false
  140. }
  141. // ExtractConditionValuesFromRequest extracts condition values from HTTP request
  142. func ExtractConditionValuesFromRequest(r *http.Request) map[string][]string {
  143. values := make(map[string][]string)
  144. // AWS condition keys
  145. // Extract IP address without port for proper IP matching
  146. host, _, err := net.SplitHostPort(r.RemoteAddr)
  147. if err != nil {
  148. // Log a warning if splitting fails
  149. glog.Warningf("Failed to parse IP address from RemoteAddr %q: %v", r.RemoteAddr, err)
  150. // If splitting fails, use the original RemoteAddr (might be just IP without port)
  151. host = r.RemoteAddr
  152. }
  153. values["aws:SourceIp"] = []string{host}
  154. values["aws:SecureTransport"] = []string{fmt.Sprintf("%t", r.TLS != nil)}
  155. // Use AWS standard condition key for current time
  156. values["aws:CurrentTime"] = []string{time.Now().Format(time.RFC3339)}
  157. // Keep RequestTime for backward compatibility
  158. values["aws:RequestTime"] = []string{time.Now().Format(time.RFC3339)}
  159. // S3 specific condition keys
  160. if userAgent := r.Header.Get("User-Agent"); userAgent != "" {
  161. values["aws:UserAgent"] = []string{userAgent}
  162. }
  163. if referer := r.Header.Get("Referer"); referer != "" {
  164. values["aws:Referer"] = []string{referer}
  165. }
  166. // S3 object-level conditions
  167. if r.Method == "GET" || r.Method == "HEAD" {
  168. values["s3:ExistingObjectTag"] = extractObjectTags(r)
  169. }
  170. // S3 bucket-level conditions
  171. if delimiter := r.URL.Query().Get("delimiter"); delimiter != "" {
  172. values["s3:delimiter"] = []string{delimiter}
  173. }
  174. if prefix := r.URL.Query().Get("prefix"); prefix != "" {
  175. values["s3:prefix"] = []string{prefix}
  176. }
  177. if maxKeys := r.URL.Query().Get("max-keys"); maxKeys != "" {
  178. values["s3:max-keys"] = []string{maxKeys}
  179. }
  180. // Authentication method
  181. if authHeader := r.Header.Get("Authorization"); authHeader != "" {
  182. if strings.HasPrefix(authHeader, "AWS4-HMAC-SHA256") {
  183. values["s3:authType"] = []string{"REST-HEADER"}
  184. } else if strings.HasPrefix(authHeader, "AWS ") {
  185. values["s3:authType"] = []string{"REST-HEADER"}
  186. }
  187. } else if r.URL.Query().Get("AWSAccessKeyId") != "" {
  188. values["s3:authType"] = []string{"REST-QUERY-STRING"}
  189. }
  190. // HTTP method
  191. values["s3:RequestMethod"] = []string{r.Method}
  192. // Extract custom headers
  193. for key, headerValues := range r.Header {
  194. if strings.HasPrefix(strings.ToLower(key), "x-amz-") {
  195. values[strings.ToLower(key)] = headerValues
  196. }
  197. }
  198. return values
  199. }
  200. // extractObjectTags extracts object tags from request (placeholder implementation)
  201. func extractObjectTags(r *http.Request) []string {
  202. // This would need to be implemented based on how object tags are stored
  203. // For now, return empty slice
  204. return []string{}
  205. }
  206. // BuildResourceArn builds an ARN for the given bucket and object
  207. func BuildResourceArn(bucketName, objectName string) string {
  208. if objectName == "" {
  209. return fmt.Sprintf("arn:aws:s3:::%s", bucketName)
  210. }
  211. return fmt.Sprintf("arn:aws:s3:::%s/%s", bucketName, objectName)
  212. }
  213. // BuildActionName builds a standardized action name
  214. func BuildActionName(action string) string {
  215. if strings.HasPrefix(action, "s3:") {
  216. return action
  217. }
  218. return fmt.Sprintf("s3:%s", action)
  219. }
  220. // IsReadAction checks if an action is a read action
  221. func IsReadAction(action string) bool {
  222. readActions := []string{
  223. "s3:GetObject",
  224. "s3:GetObjectVersion",
  225. "s3:GetObjectAcl",
  226. "s3:GetObjectVersionAcl",
  227. "s3:GetObjectTagging",
  228. "s3:GetObjectVersionTagging",
  229. "s3:ListBucket",
  230. "s3:ListBucketVersions",
  231. "s3:GetBucketLocation",
  232. "s3:GetBucketVersioning",
  233. "s3:GetBucketAcl",
  234. "s3:GetBucketCors",
  235. "s3:GetBucketPolicy",
  236. "s3:GetBucketTagging",
  237. "s3:GetBucketNotification",
  238. "s3:GetBucketObjectLockConfiguration",
  239. "s3:GetObjectRetention",
  240. "s3:GetObjectLegalHold",
  241. }
  242. for _, readAction := range readActions {
  243. if action == readAction {
  244. return true
  245. }
  246. }
  247. return false
  248. }
  249. // IsWriteAction checks if an action is a write action
  250. func IsWriteAction(action string) bool {
  251. writeActions := []string{
  252. "s3:PutObject",
  253. "s3:PutObjectAcl",
  254. "s3:PutObjectTagging",
  255. "s3:DeleteObject",
  256. "s3:DeleteObjectVersion",
  257. "s3:DeleteObjectTagging",
  258. "s3:AbortMultipartUpload",
  259. "s3:ListMultipartUploads",
  260. "s3:ListParts",
  261. "s3:PutBucketAcl",
  262. "s3:PutBucketCors",
  263. "s3:PutBucketPolicy",
  264. "s3:PutBucketTagging",
  265. "s3:PutBucketNotification",
  266. "s3:PutBucketVersioning",
  267. "s3:DeleteBucketPolicy",
  268. "s3:DeleteBucketTagging",
  269. "s3:DeleteBucketCors",
  270. "s3:PutBucketObjectLockConfiguration",
  271. "s3:PutObjectRetention",
  272. "s3:PutObjectLegalHold",
  273. "s3:BypassGovernanceRetention",
  274. }
  275. for _, writeAction := range writeActions {
  276. if action == writeAction {
  277. return true
  278. }
  279. }
  280. return false
  281. }
  282. // GetBucketNameFromArn extracts bucket name from ARN
  283. func GetBucketNameFromArn(arn string) string {
  284. if strings.HasPrefix(arn, "arn:aws:s3:::") {
  285. parts := strings.SplitN(arn[13:], "/", 2)
  286. return parts[0]
  287. }
  288. return ""
  289. }
  290. // GetObjectNameFromArn extracts object name from ARN
  291. func GetObjectNameFromArn(arn string) string {
  292. if strings.HasPrefix(arn, "arn:aws:s3:::") {
  293. parts := strings.SplitN(arn[13:], "/", 2)
  294. if len(parts) > 1 {
  295. return parts[1]
  296. }
  297. }
  298. return ""
  299. }
  300. // HasPolicyForBucket checks if a bucket has a policy
  301. func (engine *PolicyEngine) HasPolicyForBucket(bucketName string) bool {
  302. engine.mutex.RLock()
  303. defer engine.mutex.RUnlock()
  304. _, exists := engine.contexts[bucketName]
  305. return exists
  306. }
  307. // GetPolicyStatements returns all policy statements for a bucket
  308. func (engine *PolicyEngine) GetPolicyStatements(bucketName string) []PolicyStatement {
  309. engine.mutex.RLock()
  310. defer engine.mutex.RUnlock()
  311. context, exists := engine.contexts[bucketName]
  312. if !exists {
  313. return nil
  314. }
  315. return context.policy.Document.Statement
  316. }
  317. // ValidatePolicyForBucket validates if a policy is valid for a bucket
  318. func (engine *PolicyEngine) ValidatePolicyForBucket(bucketName string, policyJSON string) error {
  319. policy, err := ParsePolicy(policyJSON)
  320. if err != nil {
  321. return err
  322. }
  323. // Additional validation specific to the bucket
  324. for _, stmt := range policy.Statement {
  325. resources := normalizeToStringSlice(stmt.Resource)
  326. for _, resource := range resources {
  327. if resourceBucket := GetBucketFromResource(resource); resourceBucket != "" {
  328. if resourceBucket != bucketName {
  329. return fmt.Errorf("policy resource %s does not match bucket %s", resource, bucketName)
  330. }
  331. }
  332. }
  333. }
  334. return nil
  335. }
  336. // ClearAllPolicies clears all bucket policies
  337. func (engine *PolicyEngine) ClearAllPolicies() {
  338. engine.mutex.Lock()
  339. defer engine.mutex.Unlock()
  340. engine.contexts = make(map[string]*PolicyEvaluationContext)
  341. glog.V(2).Info("Cleared all bucket policies")
  342. }
  343. // GetAllBucketsWithPolicies returns all buckets that have policies
  344. func (engine *PolicyEngine) GetAllBucketsWithPolicies() []string {
  345. engine.mutex.RLock()
  346. defer engine.mutex.RUnlock()
  347. buckets := make([]string, 0, len(engine.contexts))
  348. for bucketName := range engine.contexts {
  349. buckets = append(buckets, bucketName)
  350. }
  351. return buckets
  352. }
  353. // EvaluatePolicyForRequest evaluates policy for an HTTP request
  354. func (engine *PolicyEngine) EvaluatePolicyForRequest(bucketName, objectName, action, principal string, r *http.Request) PolicyEvaluationResult {
  355. resource := BuildResourceArn(bucketName, objectName)
  356. actionName := BuildActionName(action)
  357. conditions := ExtractConditionValuesFromRequest(r)
  358. args := &PolicyEvaluationArgs{
  359. Action: actionName,
  360. Resource: resource,
  361. Principal: principal,
  362. Conditions: conditions,
  363. }
  364. return engine.EvaluatePolicy(bucketName, args)
  365. }