auth_credentials.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. package s3api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "slices"
  9. "strings"
  10. "sync"
  11. "github.com/seaweedfs/seaweedfs/weed/credential"
  12. "github.com/seaweedfs/seaweedfs/weed/filer"
  13. "github.com/seaweedfs/seaweedfs/weed/glog"
  14. "github.com/seaweedfs/seaweedfs/weed/kms"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
  17. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  18. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  19. // Import KMS providers to register them
  20. _ "github.com/seaweedfs/seaweedfs/weed/kms/aws"
  21. // _ "github.com/seaweedfs/seaweedfs/weed/kms/azure" // TODO: Fix Azure SDK compatibility issues
  22. _ "github.com/seaweedfs/seaweedfs/weed/kms/gcp"
  23. _ "github.com/seaweedfs/seaweedfs/weed/kms/local"
  24. _ "github.com/seaweedfs/seaweedfs/weed/kms/openbao"
  25. "google.golang.org/grpc"
  26. )
  27. type Action string
  28. type Iam interface {
  29. Check(f http.HandlerFunc, actions ...Action) http.HandlerFunc
  30. }
  31. type IdentityAccessManagement struct {
  32. m sync.RWMutex
  33. identities []*Identity
  34. accessKeyIdent map[string]*Identity
  35. accounts map[string]*Account
  36. emailAccount map[string]*Account
  37. hashes map[string]*sync.Pool
  38. hashCounters map[string]*int32
  39. identityAnonymous *Identity
  40. hashMu sync.RWMutex
  41. domain string
  42. isAuthEnabled bool
  43. credentialManager *credential.CredentialManager
  44. filerClient filer_pb.SeaweedFilerClient
  45. grpcDialOption grpc.DialOption
  46. // IAM Integration for advanced features
  47. iamIntegration *S3IAMIntegration
  48. }
  49. type Identity struct {
  50. Name string
  51. Account *Account
  52. Credentials []*Credential
  53. Actions []Action
  54. PrincipalArn string // ARN for IAM authorization (e.g., "arn:seaweed:iam::user/username")
  55. }
  56. // Account represents a system user, a system user can
  57. // configure multiple IAM-Users, IAM-Users can configure
  58. // permissions respectively, and each IAM-User can
  59. // configure multiple security credentials
  60. type Account struct {
  61. //Name is also used to display the "DisplayName" as the owner of the bucket or object
  62. DisplayName string
  63. EmailAddress string
  64. //Id is used to identify an Account when granting cross-account access(ACLs) to buckets and objects
  65. Id string
  66. }
  67. // Predefined Accounts
  68. var (
  69. // AccountAdmin is used as the default account for IAM-Credentials access without Account configured
  70. AccountAdmin = Account{
  71. DisplayName: "admin",
  72. EmailAddress: "admin@example.com",
  73. Id: s3_constants.AccountAdminId,
  74. }
  75. // AccountAnonymous is used to represent the account for anonymous access
  76. AccountAnonymous = Account{
  77. DisplayName: "anonymous",
  78. EmailAddress: "anonymous@example.com",
  79. Id: s3_constants.AccountAnonymousId,
  80. }
  81. )
  82. type Credential struct {
  83. AccessKey string
  84. SecretKey string
  85. }
  86. // "Permission": "FULL_CONTROL"|"WRITE"|"WRITE_ACP"|"READ"|"READ_ACP"
  87. func (action Action) getPermission() Permission {
  88. switch act := strings.Split(string(action), ":")[0]; act {
  89. case s3_constants.ACTION_ADMIN:
  90. return Permission("FULL_CONTROL")
  91. case s3_constants.ACTION_WRITE:
  92. return Permission("WRITE")
  93. case s3_constants.ACTION_WRITE_ACP:
  94. return Permission("WRITE_ACP")
  95. case s3_constants.ACTION_READ:
  96. return Permission("READ")
  97. case s3_constants.ACTION_READ_ACP:
  98. return Permission("READ_ACP")
  99. default:
  100. return Permission("")
  101. }
  102. }
  103. func NewIdentityAccessManagement(option *S3ApiServerOption) *IdentityAccessManagement {
  104. return NewIdentityAccessManagementWithStore(option, "")
  105. }
  106. func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, explicitStore string) *IdentityAccessManagement {
  107. iam := &IdentityAccessManagement{
  108. domain: option.DomainName,
  109. hashes: make(map[string]*sync.Pool),
  110. hashCounters: make(map[string]*int32),
  111. }
  112. // Always initialize credential manager with fallback to defaults
  113. credentialManager, err := credential.NewCredentialManagerWithDefaults(credential.CredentialStoreTypeName(explicitStore))
  114. if err != nil {
  115. glog.Fatalf("failed to initialize credential manager: %v", err)
  116. }
  117. // For stores that need filer client details, set them
  118. if store := credentialManager.GetStore(); store != nil {
  119. if filerClientSetter, ok := store.(interface {
  120. SetFilerClient(string, grpc.DialOption)
  121. }); ok {
  122. filerClientSetter.SetFilerClient(string(option.Filer), option.GrpcDialOption)
  123. }
  124. }
  125. iam.credentialManager = credentialManager
  126. // Track whether any configuration was successfully loaded
  127. configLoaded := false
  128. // First, try to load configurations from file or filer
  129. if option.Config != "" {
  130. glog.V(3).Infof("loading static config file %s", option.Config)
  131. if err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
  132. glog.Fatalf("fail to load config file %s: %v", option.Config, err)
  133. }
  134. // Mark as loaded since an explicit config file was provided
  135. // This prevents fallback to environment variables even if no identities were loaded
  136. // (e.g., config file contains only KMS settings)
  137. configLoaded = true
  138. } else {
  139. glog.V(3).Infof("no static config file specified... loading config from credential manager")
  140. if err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {
  141. glog.Warningf("fail to load config: %v", err)
  142. } else {
  143. // Check if any identities were actually loaded from filer
  144. iam.m.RLock()
  145. if len(iam.identities) > 0 {
  146. configLoaded = true
  147. }
  148. iam.m.RUnlock()
  149. }
  150. }
  151. // Only use environment variables as fallback if no configuration was loaded
  152. if !configLoaded {
  153. accessKeyId := os.Getenv("AWS_ACCESS_KEY_ID")
  154. secretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
  155. if accessKeyId != "" && secretAccessKey != "" {
  156. glog.V(0).Infof("No S3 configuration found, using AWS environment variables as fallback")
  157. // Create environment variable identity name
  158. identityNameSuffix := accessKeyId
  159. if len(accessKeyId) > 8 {
  160. identityNameSuffix = accessKeyId[:8]
  161. }
  162. // Create admin identity with environment variable credentials
  163. envIdentity := &Identity{
  164. Name: "admin-" + identityNameSuffix,
  165. Account: &AccountAdmin,
  166. Credentials: []*Credential{
  167. {
  168. AccessKey: accessKeyId,
  169. SecretKey: secretAccessKey,
  170. },
  171. },
  172. Actions: []Action{
  173. s3_constants.ACTION_ADMIN,
  174. },
  175. }
  176. // Set as the only configuration
  177. iam.m.Lock()
  178. if len(iam.identities) == 0 {
  179. iam.identities = []*Identity{envIdentity}
  180. iam.accessKeyIdent = map[string]*Identity{accessKeyId: envIdentity}
  181. iam.isAuthEnabled = true
  182. }
  183. iam.m.Unlock()
  184. glog.V(0).Infof("Added admin identity from AWS environment variables: %s", envIdentity.Name)
  185. }
  186. }
  187. return iam
  188. }
  189. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFiler(option *S3ApiServerOption) error {
  190. return iam.LoadS3ApiConfigurationFromCredentialManager()
  191. }
  192. func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName string) error {
  193. content, readErr := os.ReadFile(fileName)
  194. if readErr != nil {
  195. glog.Warningf("fail to read %s : %v", fileName, readErr)
  196. return fmt.Errorf("fail to read %s : %v", fileName, readErr)
  197. }
  198. // Initialize KMS if configuration contains KMS settings
  199. if err := iam.initializeKMSFromConfig(content); err != nil {
  200. glog.Warningf("KMS initialization failed: %v", err)
  201. }
  202. return iam.LoadS3ApiConfigurationFromBytes(content)
  203. }
  204. func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromBytes(content []byte) error {
  205. s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
  206. if err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {
  207. glog.Warningf("unmarshal error: %v", err)
  208. return fmt.Errorf("unmarshal error: %w", err)
  209. }
  210. if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
  211. return err
  212. }
  213. if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
  214. return err
  215. }
  216. return nil
  217. }
  218. func (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {
  219. var identities []*Identity
  220. var identityAnonymous *Identity
  221. accessKeyIdent := make(map[string]*Identity)
  222. accounts := make(map[string]*Account)
  223. emailAccount := make(map[string]*Account)
  224. foundAccountAdmin := false
  225. foundAccountAnonymous := false
  226. for _, account := range config.Accounts {
  227. glog.V(3).Infof("loading account name=%s, id=%s", account.DisplayName, account.Id)
  228. switch account.Id {
  229. case AccountAdmin.Id:
  230. AccountAdmin = Account{
  231. Id: account.Id,
  232. DisplayName: account.DisplayName,
  233. EmailAddress: account.EmailAddress,
  234. }
  235. accounts[account.Id] = &AccountAdmin
  236. foundAccountAdmin = true
  237. case AccountAnonymous.Id:
  238. AccountAnonymous = Account{
  239. Id: account.Id,
  240. DisplayName: account.DisplayName,
  241. EmailAddress: account.EmailAddress,
  242. }
  243. accounts[account.Id] = &AccountAnonymous
  244. foundAccountAnonymous = true
  245. default:
  246. t := Account{
  247. Id: account.Id,
  248. DisplayName: account.DisplayName,
  249. EmailAddress: account.EmailAddress,
  250. }
  251. accounts[account.Id] = &t
  252. }
  253. if account.EmailAddress != "" {
  254. emailAccount[account.EmailAddress] = accounts[account.Id]
  255. }
  256. }
  257. if !foundAccountAdmin {
  258. accounts[AccountAdmin.Id] = &AccountAdmin
  259. emailAccount[AccountAdmin.EmailAddress] = &AccountAdmin
  260. }
  261. if !foundAccountAnonymous {
  262. accounts[AccountAnonymous.Id] = &AccountAnonymous
  263. emailAccount[AccountAnonymous.EmailAddress] = &AccountAnonymous
  264. }
  265. for _, ident := range config.Identities {
  266. glog.V(3).Infof("loading identity %s", ident.Name)
  267. t := &Identity{
  268. Name: ident.Name,
  269. Credentials: nil,
  270. Actions: nil,
  271. PrincipalArn: generatePrincipalArn(ident.Name),
  272. }
  273. switch {
  274. case ident.Name == AccountAnonymous.Id:
  275. t.Account = &AccountAnonymous
  276. identityAnonymous = t
  277. case ident.Account == nil:
  278. t.Account = &AccountAdmin
  279. default:
  280. if account, ok := accounts[ident.Account.Id]; ok {
  281. t.Account = account
  282. } else {
  283. t.Account = &AccountAdmin
  284. glog.Warningf("identity %s is associated with a non exist account ID, the association is invalid", ident.Name)
  285. }
  286. }
  287. for _, action := range ident.Actions {
  288. t.Actions = append(t.Actions, Action(action))
  289. }
  290. for _, cred := range ident.Credentials {
  291. t.Credentials = append(t.Credentials, &Credential{
  292. AccessKey: cred.AccessKey,
  293. SecretKey: cred.SecretKey,
  294. })
  295. accessKeyIdent[cred.AccessKey] = t
  296. }
  297. identities = append(identities, t)
  298. }
  299. iam.m.Lock()
  300. // atomically switch
  301. iam.identities = identities
  302. iam.identityAnonymous = identityAnonymous
  303. iam.accounts = accounts
  304. iam.emailAccount = emailAccount
  305. iam.accessKeyIdent = accessKeyIdent
  306. if !iam.isAuthEnabled { // one-directional, no toggling
  307. iam.isAuthEnabled = len(identities) > 0
  308. }
  309. iam.m.Unlock()
  310. return nil
  311. }
  312. func (iam *IdentityAccessManagement) isEnabled() bool {
  313. return iam.isAuthEnabled
  314. }
  315. func (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {
  316. iam.m.RLock()
  317. defer iam.m.RUnlock()
  318. if ident, ok := iam.accessKeyIdent[accessKey]; ok {
  319. for _, credential := range ident.Credentials {
  320. if credential.AccessKey == accessKey {
  321. return ident, credential, true
  322. }
  323. }
  324. }
  325. glog.V(1).Infof("could not find accessKey %s", accessKey)
  326. return nil, nil, false
  327. }
  328. func (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {
  329. iam.m.RLock()
  330. defer iam.m.RUnlock()
  331. if iam.identityAnonymous != nil {
  332. return iam.identityAnonymous, true
  333. }
  334. return nil, false
  335. }
  336. // generatePrincipalArn generates an ARN for a user identity
  337. func generatePrincipalArn(identityName string) string {
  338. // Handle special cases
  339. switch identityName {
  340. case AccountAnonymous.Id:
  341. return "arn:seaweed:iam::user/anonymous"
  342. case AccountAdmin.Id:
  343. return "arn:seaweed:iam::user/admin"
  344. default:
  345. return fmt.Sprintf("arn:seaweed:iam::user/%s", identityName)
  346. }
  347. }
  348. func (iam *IdentityAccessManagement) GetAccountNameById(canonicalId string) string {
  349. iam.m.RLock()
  350. defer iam.m.RUnlock()
  351. if account, ok := iam.accounts[canonicalId]; ok {
  352. return account.DisplayName
  353. }
  354. return ""
  355. }
  356. func (iam *IdentityAccessManagement) GetAccountIdByEmail(email string) string {
  357. iam.m.RLock()
  358. defer iam.m.RUnlock()
  359. if account, ok := iam.emailAccount[email]; ok {
  360. return account.Id
  361. }
  362. return ""
  363. }
  364. func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {
  365. return func(w http.ResponseWriter, r *http.Request) {
  366. if !iam.isEnabled() {
  367. f(w, r)
  368. return
  369. }
  370. identity, errCode := iam.authRequest(r, action)
  371. glog.V(3).Infof("auth error: %v", errCode)
  372. if errCode == s3err.ErrNone {
  373. if identity != nil && identity.Name != "" {
  374. r.Header.Set(s3_constants.AmzIdentityId, identity.Name)
  375. }
  376. f(w, r)
  377. return
  378. }
  379. s3err.WriteErrorResponse(w, r, errCode)
  380. }
  381. }
  382. // check whether the request has valid access keys
  383. func (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {
  384. var identity *Identity
  385. var s3Err s3err.ErrorCode
  386. var found bool
  387. var authType string
  388. switch getRequestAuthType(r) {
  389. case authTypeUnknown:
  390. glog.V(3).Infof("unknown auth type")
  391. r.Header.Set(s3_constants.AmzAuthType, "Unknown")
  392. return identity, s3err.ErrAccessDenied
  393. case authTypePresignedV2, authTypeSignedV2:
  394. glog.V(3).Infof("v2 auth type")
  395. identity, s3Err = iam.isReqAuthenticatedV2(r)
  396. authType = "SigV2"
  397. case authTypeStreamingSigned, authTypeSigned, authTypePresigned:
  398. glog.V(3).Infof("v4 auth type")
  399. identity, s3Err = iam.reqSignatureV4Verify(r)
  400. authType = "SigV4"
  401. case authTypePostPolicy:
  402. glog.V(3).Infof("post policy auth type")
  403. r.Header.Set(s3_constants.AmzAuthType, "PostPolicy")
  404. return identity, s3err.ErrNone
  405. case authTypeStreamingUnsigned:
  406. glog.V(3).Infof("unsigned streaming upload")
  407. return identity, s3err.ErrNone
  408. case authTypeJWT:
  409. glog.V(3).Infof("jwt auth type detected, iamIntegration != nil? %t", iam.iamIntegration != nil)
  410. r.Header.Set(s3_constants.AmzAuthType, "Jwt")
  411. if iam.iamIntegration != nil {
  412. identity, s3Err = iam.authenticateJWTWithIAM(r)
  413. authType = "Jwt"
  414. } else {
  415. glog.V(0).Infof("IAM integration is nil, returning ErrNotImplemented")
  416. return identity, s3err.ErrNotImplemented
  417. }
  418. case authTypeAnonymous:
  419. authType = "Anonymous"
  420. if identity, found = iam.lookupAnonymous(); !found {
  421. r.Header.Set(s3_constants.AmzAuthType, authType)
  422. return identity, s3err.ErrAccessDenied
  423. }
  424. default:
  425. return identity, s3err.ErrNotImplemented
  426. }
  427. if len(authType) > 0 {
  428. r.Header.Set(s3_constants.AmzAuthType, authType)
  429. }
  430. if s3Err != s3err.ErrNone {
  431. return identity, s3Err
  432. }
  433. glog.V(3).Infof("user name: %v actions: %v, action: %v", identity.Name, identity.Actions, action)
  434. bucket, object := s3_constants.GetBucketAndObject(r)
  435. prefix := s3_constants.GetPrefix(r)
  436. // For List operations, use prefix for permission checking if available
  437. if action == s3_constants.ACTION_LIST && object == "" && prefix != "" {
  438. // List operation with prefix - check permission for the prefix path
  439. object = prefix
  440. } else if (object == "/" || object == "") && prefix != "" {
  441. // Using the aws cli with s3, and s3api, and with boto3, the object is often set to "/" or empty
  442. // but the prefix is set to the actual object key for permission checking
  443. object = prefix
  444. }
  445. // For ListBuckets, authorization is performed in the handler by iterating
  446. // through buckets and checking permissions for each. Skip the global check here.
  447. if action == s3_constants.ACTION_LIST && bucket == "" {
  448. // ListBuckets operation - authorization handled per-bucket in the handler
  449. } else {
  450. // Use enhanced IAM authorization if available, otherwise fall back to legacy authorization
  451. if iam.iamIntegration != nil {
  452. // Always use IAM when available for unified authorization
  453. if errCode := iam.authorizeWithIAM(r, identity, action, bucket, object); errCode != s3err.ErrNone {
  454. return identity, errCode
  455. }
  456. } else {
  457. // Fall back to existing authorization when IAM is not configured
  458. if !identity.canDo(action, bucket, object) {
  459. return identity, s3err.ErrAccessDenied
  460. }
  461. }
  462. }
  463. r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
  464. return identity, s3err.ErrNone
  465. }
  466. func (identity *Identity) canDo(action Action, bucket string, objectKey string) bool {
  467. if identity.isAdmin() {
  468. return true
  469. }
  470. for _, a := range identity.Actions {
  471. // Case where the Resource provided is
  472. // "Resource": [
  473. // "arn:aws:s3:::*"
  474. // ]
  475. if a == action {
  476. return true
  477. }
  478. }
  479. if bucket == "" {
  480. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s -- bucket is empty", identity.Name, action, bucket+objectKey)
  481. return false
  482. }
  483. glog.V(3).Infof("checking if %s can perform %s on bucket '%s'", identity.Name, action, bucket+objectKey)
  484. target := string(action) + ":" + bucket + objectKey
  485. adminTarget := s3_constants.ACTION_ADMIN + ":" + bucket + objectKey
  486. limitedByBucket := string(action) + ":" + bucket
  487. adminLimitedByBucket := s3_constants.ACTION_ADMIN + ":" + bucket
  488. for _, a := range identity.Actions {
  489. act := string(a)
  490. if strings.HasSuffix(act, "*") {
  491. if strings.HasPrefix(target, act[:len(act)-1]) {
  492. return true
  493. }
  494. if strings.HasPrefix(adminTarget, act[:len(act)-1]) {
  495. return true
  496. }
  497. } else {
  498. if act == limitedByBucket {
  499. return true
  500. }
  501. if act == adminLimitedByBucket {
  502. return true
  503. }
  504. }
  505. }
  506. //log error
  507. glog.V(3).Infof("identity %s is not allowed to perform action %s on %s", identity.Name, action, bucket+objectKey)
  508. return false
  509. }
  510. func (identity *Identity) isAdmin() bool {
  511. return slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN)
  512. }
  513. // GetCredentialManager returns the credential manager instance
  514. func (iam *IdentityAccessManagement) GetCredentialManager() *credential.CredentialManager {
  515. return iam.credentialManager
  516. }
  517. // LoadS3ApiConfigurationFromCredentialManager loads configuration using the credential manager
  518. func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromCredentialManager() error {
  519. s3ApiConfiguration, err := iam.credentialManager.LoadConfiguration(context.Background())
  520. if err != nil {
  521. return fmt.Errorf("failed to load configuration from credential manager: %w", err)
  522. }
  523. return iam.loadS3ApiConfiguration(s3ApiConfiguration)
  524. }
  525. // initializeKMSFromConfig loads KMS configuration from TOML format
  526. func (iam *IdentityAccessManagement) initializeKMSFromConfig(configContent []byte) error {
  527. // JSON-only KMS configuration
  528. if err := iam.initializeKMSFromJSON(configContent); err == nil {
  529. glog.V(1).Infof("Successfully loaded KMS configuration from JSON format")
  530. return nil
  531. }
  532. glog.V(2).Infof("No KMS configuration found in S3 config - SSE-KMS will not be available")
  533. return nil
  534. }
  535. // initializeKMSFromJSON loads KMS configuration from JSON format when provided in the same file
  536. func (iam *IdentityAccessManagement) initializeKMSFromJSON(configContent []byte) error {
  537. // Parse as generic JSON and extract optional "kms" block
  538. var m map[string]any
  539. if err := json.Unmarshal([]byte(strings.TrimSpace(string(configContent))), &m); err != nil {
  540. return err
  541. }
  542. kmsVal, ok := m["kms"]
  543. if !ok {
  544. return fmt.Errorf("no KMS section found")
  545. }
  546. // Load KMS configuration directly from the parsed JSON data
  547. return kms.LoadKMSFromConfig(kmsVal)
  548. }
  549. // SetIAMIntegration sets the IAM integration for advanced authentication and authorization
  550. func (iam *IdentityAccessManagement) SetIAMIntegration(integration *S3IAMIntegration) {
  551. iam.m.Lock()
  552. defer iam.m.Unlock()
  553. iam.iamIntegration = integration
  554. }
  555. // authenticateJWTWithIAM authenticates JWT tokens using the IAM integration
  556. func (iam *IdentityAccessManagement) authenticateJWTWithIAM(r *http.Request) (*Identity, s3err.ErrorCode) {
  557. ctx := r.Context()
  558. // Use IAM integration to authenticate JWT
  559. iamIdentity, errCode := iam.iamIntegration.AuthenticateJWT(ctx, r)
  560. if errCode != s3err.ErrNone {
  561. return nil, errCode
  562. }
  563. // Convert IAMIdentity to existing Identity structure
  564. identity := &Identity{
  565. Name: iamIdentity.Name,
  566. Account: iamIdentity.Account,
  567. Actions: []Action{}, // Empty - authorization handled by policy engine
  568. }
  569. // Store session info in request headers for later authorization
  570. r.Header.Set("X-SeaweedFS-Session-Token", iamIdentity.SessionToken)
  571. r.Header.Set("X-SeaweedFS-Principal", iamIdentity.Principal)
  572. return identity, s3err.ErrNone
  573. }
  574. // authorizeWithIAM authorizes requests using the IAM integration policy engine
  575. func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode {
  576. ctx := r.Context()
  577. // Get session info from request headers (for JWT-based authentication)
  578. sessionToken := r.Header.Get("X-SeaweedFS-Session-Token")
  579. principal := r.Header.Get("X-SeaweedFS-Principal")
  580. // Create IAMIdentity for authorization
  581. iamIdentity := &IAMIdentity{
  582. Name: identity.Name,
  583. Account: identity.Account,
  584. }
  585. // Handle both session-based (JWT) and static-key-based (V4 signature) principals
  586. if sessionToken != "" && principal != "" {
  587. // JWT-based authentication - use session token and principal from headers
  588. iamIdentity.Principal = principal
  589. iamIdentity.SessionToken = sessionToken
  590. glog.V(3).Infof("Using JWT-based IAM authorization for principal: %s", principal)
  591. } else if identity.PrincipalArn != "" {
  592. // V4 signature authentication - use principal ARN from identity
  593. iamIdentity.Principal = identity.PrincipalArn
  594. iamIdentity.SessionToken = "" // No session token for static credentials
  595. glog.V(3).Infof("Using V4 signature IAM authorization for principal: %s", identity.PrincipalArn)
  596. } else {
  597. glog.V(3).Info("No valid principal information for IAM authorization")
  598. return s3err.ErrAccessDenied
  599. }
  600. // Use IAM integration for authorization
  601. return iam.iamIntegration.AuthorizeAction(ctx, iamIdentity, action, bucket, object, r)
  602. }