This repository was archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
Sync android apps from json file #1191
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
adabc27
Unmarshall response from json file
whaught 7a04236
Moar
whaught fc7dd21
comments
whaught e484375
timeout and size limit
whaught 10bd5e5
some review things
whaught 628e295
populate mobile_app
whaught 1319ec9
Merge remote-tracking branch 'upstream/main' into appsync
whaught e1805ad
fix scope merge
whaught 0172f1a
skip sync if no URL configured
whaught 809fb24
move external call to clients package
whaught 4aa8234
extract processing
whaught 59db35f
add test and random name
whaught 407e778
comment
whaught 0ca798f
name collision fix
whaught 9868761
Update internal/project/random.go
whaught 7e5aec6
Update pkg/controller/appsync/appsync.go
whaught 20a490c
Update pkg/controller/appsync/appsync.go
whaught 10f529f
review things
whaught e4a02e2
Update pkg/controller/appsync/appsync.go
whaught 4d5ef7b
helper method
whaught 3a72987
handle err
whaught 51e040c
url parse
whaught 8bda709
error and random length
whaught File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Copyright 2020 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// Package project defines global project helpers. | ||
package project | ||
|
||
import ( | ||
"crypto/rand" | ||
"crypto/sha256" | ||
"encoding/base64" | ||
"fmt" | ||
) | ||
|
||
// RandomString generates a random string of 32 characters in length | ||
func RandomString() (string, error) { | ||
b := make([]byte, 512) | ||
if _, err := rand.Read(b[:]); err != nil { | ||
return "", fmt.Errorf("failed to generate random: %w", err) | ||
} | ||
return fmt.Sprintf("%x", sha256.Sum256(b[:])), nil | ||
} | ||
|
||
// RandomBase64String encodes a random base64 string of a given length. | ||
func RandomBase64String(len int) (string, error) { | ||
b := make([]byte, len) | ||
if _, err := rand.Read(b[:]); err != nil { | ||
return "", fmt.Errorf("failed to generate random: %w", err) | ||
} | ||
return base64.URLEncoding.EncodeToString(b), nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// Copyright 2020 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package clients | ||
|
||
// AppsResponse is the body for the published list of android apps. | ||
type AppsResponse struct { | ||
Apps []App `json:"apps"` | ||
} | ||
|
||
// App represents single app for the AppResponse body. | ||
type App struct { | ||
Region string `json:"region"` | ||
IsEnx bool `json:"is_enx,omitempty"` | ||
AndroidTarget `json:"android_target"` | ||
} | ||
|
||
// AndroidTarget holds the android metadata for an App of AppResponse. | ||
type AndroidTarget struct { | ||
Namespace string `json:"namespace"` | ||
PackageName string `json:"package_name"` | ||
SHA256CertFingerprints string `json:"sha256_cert_fingerprints"` | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,40 +12,152 @@ | |
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// Package appsync syncs the published list of mobile apps to this server's db. | ||
package appsync | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"net/http" | ||
"net/url" | ||
|
||
"github.com/google/exposure-notifications-verification-server/pkg/config" | ||
"github.com/google/exposure-notifications-server/pkg/logging" | ||
"github.com/google/exposure-notifications-verification-server/internal/project" | ||
"github.com/google/exposure-notifications-verification-server/pkg/clients" | ||
"github.com/google/exposure-notifications-verification-server/pkg/controller" | ||
"github.com/google/exposure-notifications-verification-server/pkg/database" | ||
"github.com/google/exposure-notifications-verification-server/pkg/render" | ||
"github.com/hashicorp/go-multierror" | ||
) | ||
|
||
// Controller is a controller for the appsync service. | ||
type Controller struct { | ||
config *config.AppSyncConfig | ||
db *database.Database | ||
h *render.Renderer | ||
} | ||
|
||
// New creates a new appsync controller. | ||
func New(config *config.AppSyncConfig, db *database.Database, h *render.Renderer) (*Controller, error) { | ||
return &Controller{ | ||
config: config, | ||
db: db, | ||
h: h, | ||
}, nil | ||
} | ||
const playStoreHost = `play.google.com/store/apps/details` | ||
|
||
// HandleSync performs the logic to sync mobile apps. | ||
func (c *Controller) HandleSync(ctx context.Context) http.Handler { | ||
func (c *Controller) HandleSync() http.Handler { | ||
type AppSyncResult struct { | ||
OK bool `json:"ok"` | ||
Errors []error `json:"errors,omitempty"` | ||
} | ||
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
// TODO(whaught): implement this | ||
controller.InternalError(w, r, c.h, errors.New("not implemented")) | ||
ctx := r.Context() | ||
apps, err := clients.AppSync(c.config.AppSyncURL, c.config.Timeout, c.config.FileSizeLimitBytes) | ||
if err != nil { | ||
controller.InternalError(w, r, c.h, err) | ||
return | ||
} | ||
|
||
// If there are any errors, return them | ||
if merr := c.syncApps(ctx, apps); merr != nil { | ||
if errs := merr.WrappedErrors(); len(errs) > 0 { | ||
c.h.RenderJSON(w, http.StatusInternalServerError, &AppSyncResult{ | ||
OK: false, | ||
Errors: errs, | ||
}) | ||
return | ||
} | ||
} | ||
c.h.RenderJSON(w, http.StatusOK, &AppSyncResult{OK: true}) | ||
}) | ||
} | ||
|
||
// syncApps looks up the realm and associated list of MobileApps for each entry of AppsResponse. Then it | ||
// checks to see if there exists an app with the AppResponse SHA hash, if not it creates a new MobileApp. | ||
func (c *Controller) syncApps(ctx context.Context, apps *clients.AppsResponse) *multierror.Error { | ||
whaught marked this conversation as resolved.
Show resolved
Hide resolved
|
||
logger := logging.FromContext(ctx).Named("appsync.syncApps") | ||
var merr *multierror.Error | ||
|
||
realms := map[string]*database.Realm{} | ||
appsByRealm := map[uint][]*database.MobileApp{} | ||
|
||
for _, app := range apps.Apps { | ||
|
||
realm, err := c.findRealmForApp(app, realms) | ||
if err != nil { | ||
merr = multierror.Append(merr, fmt.Errorf("unable to lookup realm for region %q: %w", app.Region, err)) | ||
continue | ||
} | ||
|
||
realmApps, err := c.findAppsForRealm(realm.ID, appsByRealm) | ||
if err != nil { | ||
merr = multierror.Append(merr, fmt.Errorf("unable to list apps for realm %d: %w", realm.ID, err)) | ||
continue | ||
} | ||
|
||
// Find out if this realm's applist already has an app with this fingerprint. | ||
hasSHA, hasGeneratedName := false, false | ||
for _, a := range realmApps { | ||
if a.SHA == app.SHA256CertFingerprints { | ||
hasSHA = true | ||
} | ||
if a.Name == generateAppName(app) { | ||
hasGeneratedName = true | ||
} | ||
} | ||
|
||
// Didn't find an app. make one. | ||
if !hasSHA { | ||
logger.Infow("app not found during sync, adding", "app", app) | ||
|
||
name := generateAppName(app) | ||
if hasGeneratedName { // add a random string to names on collision | ||
s, err := project.RandomBase64String(8) | ||
if err != nil { | ||
merr = multierror.Append(merr, fmt.Errorf("error generating app name: %w", err)) | ||
continue | ||
} | ||
name += " " + s | ||
} | ||
|
||
var playStoreURL = &url.URL{ | ||
Scheme: "https", | ||
Host: playStoreHost, | ||
RawQuery: "id=" + app.PackageName, | ||
} | ||
|
||
newApp := &database.MobileApp{ | ||
Name: name, | ||
RealmID: realm.ID, | ||
URL: playStoreURL.String(), | ||
OS: database.OSTypeAndroid, | ||
SHA: app.SHA256CertFingerprints, | ||
AppID: app.PackageName, | ||
} | ||
if err := c.db.SaveMobileApp(newApp, database.System); err != nil { | ||
merr = multierror.Append(merr, fmt.Errorf("failed saving mobile app: %w", err)) | ||
continue | ||
} | ||
} | ||
} | ||
return merr | ||
} | ||
|
||
func (c *Controller) findRealmForApp( | ||
app clients.App, realms map[string]*database.Realm) (*database.Realm, error) { | ||
var err error | ||
realm, has := realms[app.Region] | ||
if !has { // Find this apps region and cache it in our realms map | ||
realm, err = c.db.FindRealmByRegion(app.Region) | ||
if err != nil { | ||
return nil, err | ||
} | ||
realms[app.Region] = realm | ||
} | ||
return realm, nil | ||
} | ||
|
||
func (c *Controller) findAppsForRealm( | ||
realmID uint, appsByRealm map[uint][]*database.MobileApp) ([]*database.MobileApp, error) { | ||
var err error | ||
realmApps, has := appsByRealm[realmID] | ||
if !has { // Find all of the apps for this realm and cache that list in our appByRealmMap | ||
realmApps, err = c.db.ListActiveApps(realmID, database.WithAppOS(database.OSTypeAndroid)) | ||
if err != nil { | ||
return nil, err | ||
} | ||
appsByRealm[realmID] = realmApps | ||
} | ||
return realmApps, nil | ||
} | ||
|
||
func generateAppName(app clients.App) string { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To avoid the extra check, should we always append a random ID? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I started that way. I kind of think the random is ugly (and collisions are unlikely in the real-world) so I figured to optimize for nice names. |
||
return app.Region + " Android App" | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.