2021年3月5日 星期五

[Elasticsearch] Adjust index mapping by using reindex

最近在做的 log 遇到一開始沒有設定 index mapping type,所以 elasticsearch 自動判斷 value 給予 long type,但實際上該欄位資料應該是 float,只是剛好 index doc 那一筆是整數,讓 ES 判斷為 long。

以下範例說明: 

PUT test-index
POST test-index/_doc
{
  "name":"xxx",
  "price":22
}

建完 index 新增第一筆資料,再查詢 mapping api,會看到 price 為 long type

GET test-index/_mapping/

{
  "test-index" : {
    "mappings" : {
      "properties" : {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "price" : {
          "type" : "long"
        }
      }
    }
  }
}

接著新增其他資料,price type 也一直會是 long

POST test-index/_doc
{
  "name":"yyy",
  "price":10.5
}

下面就進入這篇的重點啦,利用 elasticsearch 提供的 reindex api 將錯誤的 type 歸正。

首先需要新增一個 backup index,然後將其 price properties mapping type 修改為 float 。

PUT test-index-bak
PUT test-index-bak/_mapping
{
  "properties": {
    "price":{
      "type":"float"
    }
  }
}

查看一下

GET test-index-bak/_mapping/field/price
{
  "test-index-bak" : {
    "mappings" : {
      "price" : {
        "full_name" : "price",
        "mapping" : {
          "price" : {
            "type" : "float"
          }
        }
      }
    }
  }
}

接著就是將原本的資料透過 reindex 匯入 backup index

POST _reindex
{
  "source": {
    "index": "test-index"
  },
  "dest": {
    "index": "test-index-bak"
  }
}

匯入完以後刪掉原有的 index,再重複一次上面的動作,只是這次是針對原有的 test-index 做操作,再將備份的資料倒回來。

DELETE test-index
PUT test-index

PUT test-index/_mapping
{
  "properties": {
    "price":{
      "type":"float"
    }
  }
}

GET test-index/_mapping/

POST _reindex
{
  "source": {
    "index": "test-index-bak"
  },
  "dest": {
    "index": "test-index"
  }
}
DELETE test-index-bak

最後刪掉 backup index 就結束啦,是不是很簡單~~

2021年1月19日 星期二

SwaggerUI 的 Content Security Policy (SCP) 設定

最近工作上用到靜態代碼分析工具,並且在修正 Critical Issue 時碰到一些問題,來分享紀錄一下

Fortify Static Code Analyzer 是一個靜態應用程式安全分析工具

我這次遇到的是 Content Security Policy (CSP) is not configured.
那什麼是 CSP 呢?看 Wiki 就知道了

Content Security Policy (CSP) is a computer security standard introduced to prevent cross-site scripting (XSS), clickjacking and other code injection attacks resulting from execution of malicious content in the trusted web page context.

https://en.wikipedia.org/wiki/Content_Security_Policy




一開始以為,喔~只要把 Content-Security-Policy: default-src 'none' 這個 Header 加上去就好了吧!沒錯,加上去再做一次 Fortify Scan 就沒有 CSP Critical Issue 了,但是 SwaggerUI 卻壞了…


因為 Swagger 的 css, js, icon 資源載入,全被 Browser 擋掉了。
這是因為 default-src 'none' 的意思是任何資源都不允許,所以必須開一些白名單讓自己網站的資源可以正常載入,最後改成這樣就正常了。

default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:;

其他相關 CSP 設定可參考這裡