go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/casviewer/appengine/main.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"context"
    19  
    20  	"cloud.google.com/go/compute/metadata"
    21  
    22  	"go.chromium.org/luci/casviewer"
    23  	"go.chromium.org/luci/server"
    24  	"go.chromium.org/luci/server/auth"
    25  	"go.chromium.org/luci/server/auth/iap"
    26  	"go.chromium.org/luci/server/router"
    27  )
    28  
    29  func main() {
    30  	ctx := context.Background()
    31  	cc := casviewer.NewClientCache(ctx)
    32  	defer cc.Clear()
    33  
    34  	server.Main(nil, nil, func(srv *server.Server) error {
    35  		authMW, err := iapAuthMW()
    36  		if err != nil {
    37  			return err
    38  		}
    39  		srv.Routes.Use(router.NewMiddlewareChain(
    40  			authMW,
    41  		))
    42  		casviewer.InstallHandlers(srv.Routes, cc, srv.Options.ImageVersion())
    43  		return nil
    44  	})
    45  }
    46  
    47  // iapAuthMW returns authentication middleware with IAPAuthMethod.
    48  func iapAuthMW() (router.Middleware, error) {
    49  	aud, err := authAudience()
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	return auth.Authenticate(
    54  		&iap.IAPAuthMethod{Aud: aud}), nil
    55  }
    56  
    57  func authAudience() (string, error) {
    58  	c := metadata.NewClient(nil)
    59  	pID, err := c.NumericProjectID()
    60  	if err != nil {
    61  		return "", err
    62  	}
    63  	// Cloud Project ID is AppEngine Application ID.
    64  	appID, err := c.ProjectID()
    65  	if err != nil {
    66  		return "", err
    67  	}
    68  	return iap.AudForGAE(pID, appID), nil
    69  }